package com.happystudy.serviceImpl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.happpystudy.service.FileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;


@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FastFileStorageClient storageClient;

    @Override
    public String doSave(MultipartFile file) throws IOException {
        InputStream is = null;
        try
            {

//                // 获取文件源
//                File source = new File("D:\\HappyStudyPro\\HappyStudyApp\\happy-study\\src\\main\\resources\\static\\image\\LOGO.png");
//                // 获取文件流
//                is = new FileInputStream(source);

                is = file.getInputStream();

                // 进行文件上传
                StorePath storePath = storageClient.uploadFile(is, file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
                // 获得文件上传后访问地址
                // 打印访问地址
                return storePath.getFullPath();
            }
        catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
        finally
            {
            try
                {
                    if(is != null)
                    {
                        // 关闭流资源
                        is.close();
                    }
                }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }


    @Override
    public byte[] doDownload(String fullPath){
        // 文件访问地址

        // 分离文件分组
        String group = fullPath.substring(0, fullPath.indexOf("/"));
        // 分离文件路径
        String path = fullPath.substring(fullPath.indexOf("/") + 1);
        // 进行文件下载

        return storageClient.downloadFile(group, path, new DownloadByteArray());

    }


    public void doDelect(String fullPath){
        storageClient.deleteFile(fullPath);
    }

}
